//
//  WanTableViewController.swift
//  YeKa
//
//  Created by Gina on 15/10/13.
//  Copyright © 2015年 Gina. All rights reserved.
//

import UIKit

class WanTableViewController: UITableViewController {

    
    // 轮播的所有图片
    private var imgs: [ImageLoop]?
    // 玩的表格数据
    private var wanlist: [WanList]? {
        didSet {
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 判断如果当前iPhone系统大于等于7.0加这个判断，是为了防止切换tabbar后，UITableView被Nav遮盖。
        if Double(UIDevice.currentDevice().systemVersion) >= 7.0 {
            edgesForExtendedLayout = UIRectEdge.None
        }
        
        refreshControl = YeKaRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        
        loadData()
    }
    
    // MARK:    加载数据
    func loadData(){
        
        refreshControl?.beginRefreshing()
        
        // 加载图片
        ImageLoop.loadImageLoops { (dataList, error) -> () in
            self.imgs = dataList
            self.showImageLoop()
            
        }
        
        // 加载TableView数据
        WanList.loadWanList { (dataList, error) -> () in
            self.wanlist = dataList
            self.refreshControl?.endRefreshing()
        }
    }
    
    // MARK:    数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // 两个问号代表如果数组为空，则返回0
        return wanlist?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell: WanCellTableViewCell = WanCellTableViewCell.loadCellWithTableView(tableView)
        cell.wan = wanlist![indexPath.row] as WanList
        return cell
        
    }
    
    
    
    // MARK:    HeaderView图片轮播器
    var circleView: CirCleView!
    private func showImageLoop(){
        
        self.automaticallyAdjustsScrollViewInsets = false
 
        var imageArray = [String]()
        for im in imgs! {
            imageArray.append(im.imageUrl!)
        }
        
        circleView = CirCleView(frame: CGRectMake(CGFloat(10), CGFloat(0), view.frame.width-20, CGFloat(200)), imageArray: imageArray)
        
        let headView: UIView = UIView(frame: CGRectMake(0, 0, view.frame.width, 200))
        
        headView.addSubview(circleView)
        
        tableView.tableHeaderView = headView

    }
    

}
